package com.freshman_registration.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.freshman_registration.mapper.StudentMapper;
import com.freshman_registration.pojo.Students;
import com.freshman_registration.service.StudentService;
import com.freshman_registration.util.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/student")
@Slf4j
public class StudentController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private StudentMapper studentMapper;
    @PostMapping("/insert")
    //添加学生信息
    public Result<?> insertStudent(@RequestBody Students student){
        return studentService.insertStudent(student);
    }
    //修改学生信息
    @PutMapping("/update")
    public Result<?> updateStudent(@RequestBody Students student){
        return studentService.updateStudent(student);
    }

    //根据学号修改学生信息
    @PutMapping("/updateStudentByStudentId")
    public Result<?> updateStudentByStudentId(@RequestBody Students student){
        return studentService.updateStudentByStudentId(student);
    }

    //删除学生信息
    @DeleteMapping("/delete/{id}")
    public Result<?> deleteStudent(@PathVariable Integer id){
        return studentService.deleteStudent(id);
    }

    //分页查询所有学生信息
    @GetMapping("/queryAll")
    public Result<?> queryAllStudents(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "5") Integer pageSize){
      Page page = studentService.queryAllStudents(currentPage, pageSize);
      PageInfo<Object> pageInfo = new PageInfo<>(page);
      return Result.success(pageInfo);
    }


    //根据学号查询
    @GetMapping("/queryStudentByStudentId")
    public Result<Students> queryStudentByStudentId(String studentId){
        return studentService.queryStudentByStudentId(studentId);
    }

   //学生登录
   @PostMapping("/login")
   public Result<?> loginStudent(@RequestBody Students students){
       return studentService.loginWithDorm(students.getStudentId(), students.getPassword());
   }
    //导出Excel
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) {
        studentService.exportExcel(response);
    }

    /**
     * 文件导入模板
     * @param
     * @return
     * @throws IOException
     */
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        studentService.importTemplate(response);
    }

    @PostMapping("/import")
    public Result<?> importExcel(MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail("请选择要导入的Excel文件");
        }

        InputStream is = null;
        ExcelReader excelReader = null;
        int successCount = 0;
        int failCount = 0;
        StringBuilder errorMsg = new StringBuilder();

        try {
            // 获取输入流
            is = file.getInputStream();
            // 读取Excel
            excelReader = ExcelUtil.getReader(is);
            List<Students> studentsList = excelReader.readAll(Students.class);

            if (studentsList == null || studentsList.isEmpty()) {
                return Result.fail("Excel文件中没有数据");
            }

            for (Students student : studentsList) {
                try {

                    if (student.getName() == null || student.getName().trim().isEmpty()) {
                        failCount++;
                        errorMsg.append("用户名不能为空; ");
                        continue;
                    }

                    Result<?> result = studentService.insertStudent(student);
                    if (result != null && "操作成功".equals(result.getMessage())) {
                        successCount++;
                    } else {
                        failCount++;
                        errorMsg.append("用户 <b>").append(student.getName()).append("</b> 插入失败; ");
                    }
                } catch (Exception e) {
                    failCount++;
                    errorMsg.append("用户 <b>").append(student.getName()).append("</b> 插入异常: ")
                            .append(e.getMessage()).append("; ");
                    // 记录详细异常日志
                    log.error("导入用户异常", e);
                }
            }

            // 构建返回结果
            if (failCount > 0) {
                return Result.success("数据导入完成，成功: <b>" + successCount + "</b>条，失败: <b>" + failCount + "</b>条。"
                        + errorMsg.toString());
            } else {
                return Result.success("数据导入成功，共导入" + successCount + "条记录");
            }

        } catch (IOException e) {
            log.error("Excel文件读取失败", e);
            return Result.fail("文件读取失败：" + e.getMessage());
        } finally {
            // 关闭资源
            if (excelReader != null) {
                try {
                    excelReader.close();
                } catch (Exception e) {
                    log.error("ExcelReader关闭失败", e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error("输入流关闭失败", e);
                }
            }
        }
    }


    //批量删除
    @DeleteMapping("/deleteBatch")
    public Result<?> deleteBatch(@RequestParam List<Integer> ids) {
        return studentService.deleteBatchStudent(ids);
    }
    //状态更新
    @PutMapping("/students/{id}/status")
    public Result<Integer> updateStatusStudent(@PathVariable Integer id,
                                        @RequestBody Map<String,String> body) {
        String accountStatus = body.get("accountStatus");
        if (accountStatus == null) return Result.fail("accountStatus 不能为空");
        return studentService.updateStatusStudent(id, accountStatus);
    }


    //根据状态姓名学号分页查询
    @GetMapping("/query")
    public Result<PageInfo<Students>> queryStudents(
            @RequestParam(defaultValue = "1") Integer currentPage,  // 前端传递的页码
            @RequestParam(defaultValue = "5") Integer pageSize,     // 前端传递的页大小
            @RequestParam(required = false) Integer accountStatus,
            @RequestParam(required = false) String studentId,
            @RequestParam(required = false) String name) {
        // 调用修改后的Service方法（传递currentPage和pageSize）
        PageInfo<Students> pageInfo = studentService.queryStudents(accountStatus, studentId,name, currentPage, pageSize);
        return Result.success(pageInfo);
    }


    //更改密码
    @PutMapping("/updatePassword")
    public Result<?> updatePassword(@RequestBody Map<String, String> body) {
        String studentId = body.get("studentId");
        String password = body.get("password");
        return studentService.updatePassword(studentId, password);
    }
    @PostMapping("/verifyPassword")
    public Result<?> verifyPassword(@RequestBody Map<String,String> params) {
        String studentId = params.get("studentId");
        String password  = params.get("password");

        Students student = studentMapper.queryStudentByStudentId(studentId);
        if (student == null) {
            return Result.fail("学号不存在");
        }
        String md5Input = SecureUtil.md5(password.trim());
        if (md5Input.equals(student.getPassword())) {
            return Result.success("密码正确");
        }
        return Result.fail("密码错误");
    }


    //更新头像
    @PutMapping("/updatePhoto")
    public Result<?> updatePhoto(@RequestBody Map<String, String> body) {
        String studentId = body.get("studentId");
        String photo = body.get("photo");
        return studentService.updatePhoto(studentId, photo);
    }
}
